package hawk.example.juni5.launcher;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;

import org.junit.platform.launcher.LauncherInterceptor;

public class CustomLauncherInterceptor implements LauncherInterceptor {

	private final URLClassLoader customClassLoader;

	public CustomLauncherInterceptor(URLClassLoader customClassLoader) throws Exception {
		ClassLoader parent = Thread.currentThread().getContextClassLoader();
		this.customClassLoader = new URLClassLoader(new URL[] { URI.create("some.jar").toURL() }, parent);
	}

	@Override
	public <T> T intercept(Invocation<T> invocation) {
		Thread currentThread = Thread.currentThread();
		ClassLoader originalClassLoader = currentThread.getContextClassLoader();
		currentThread.setContextClassLoader(customClassLoader);
		try {
			return invocation.proceed();
		} finally {
			currentThread.setContextClassLoader(originalClassLoader);
		}
	}

	@Override
	public void close() {
		try {
			customClassLoader.close();
		} catch (IOException e) {
			throw new UncheckedIOException("Failed to close custom class loader", e);
		}
	}

}
